<template>
  <div>
    <Echart
        id="nanjingHeatMap"
        ref="heatMapRef"
        :options="options"
        height="610px"
        width="440px"
    ></Echart>
  </div>
</template>

<script>
import Echart from '@/common/echart';
import '@/common/map/jiangsu/nanjing';

export default {
  data() {
    return {
      options: {},
      intervalId: null,
      preSelectMapIndex: -1,
      // 热力图点的经纬度数据
      heatGeoCoord: {
        高淳区: [118.87589, 31.327132],
        溧水区: [119.028732, 31.653061],
        六合区: [118.85065, 32.340655],
        江宁区: [118.850621, 31.953418],
        雨花台区: [118.77207, 31.995946],
        栖霞区: [118.808702, 32.102147],
        浦口区: [118.625307, 32.05839],
        鼓楼区: [118.769739, 32.066966],
        建邺区: [118.732688, 32.004538],
        秦淮区: [118.786088, 32.033818],
        玄武区: [118.792199, 32.050678]
      }
    };
  },
  components: {
    Echart
  },
  props: {
    cdata: {
      type: Array,
      default: () => []
    }
  },
  watch: {
    cdata: {
      handler(newData) {
        this.initHeatMapOptions(newData);
        this.handleMapRandomSelect();
      },
      immediate: true,
      deep: true
    }
  },
  beforeDestroy() {
    if (this.intervalId) {
      clearInterval(this.intervalId);
    }
  },
  methods: {
    // 初始化热力图配置
    initHeatMapOptions(data) {
      // 转换热力数据为[经度, 纬度, 数值]格式
      const heatData = data.map(item => {
        const coord = this.heatGeoCoord[item.name];
        return coord ? [...coord, item.value || 0] : null;
      }).filter(Boolean);

      this.options = {
        tooltip: {
          trigger: 'item',
          formatter: params => {
            return `${params.name || '区域'}: ${params.value[2] || 0}`;
          },
          textStyle: {
            fontSize: 14
          }
        },
        // 热力图视觉映射
        visualMap: {
          type: 'continuous',
          min: Math.min(...heatData.map(item => item[2]) || [0]),
          max: Math.max(...heatData.map(item => item[2]) || [10]),
          calculable: true,
          show: true,
          top: 'bottom',
          left: 'right',
          textStyle: {
            color: '#fff'
          },
          inRange: {
            color: [
              'rgba(55, 162, 255, 0.3)',
              'rgba(55, 162, 255, 0.6)',
              'rgba(55, 162, 255, 0.8)',
              'rgba(55, 162, 255, 1)',
              'rgba(255, 255, 0, 1)',
              'rgba(255, 102, 0, 1)'
            ]
          }
        },
        geo: {
          show: true,
          map: '南京',
          aspectScale: 0.85,
          zoom: 1.2,
          top: '10%',
          left: '16%',
          roam: false,
          itemStyle: {
            normal: {
              areaColor: 'rgba(19, 54, 162, 0.3)',
              borderColor: 'rgba(0, 242, 252, 0.3)',
              borderWidth: 1
            },
            emphasis: {
              areaColor: 'rgba(79, 127, 255, 0.5)'
            }
          },
          label: {
            show: true,
            textStyle: {
              color: '#efefef',
              fontSize: 12
            }
          }
        },
        series: [
          // 热力图系列
          {
            type: 'heatmap',
            coordinateSystem: 'geo',
            data: heatData,
            blurSize: 15, // 热力模糊大小
            pointSize: 10, // 点大小
            // 热力图权重配置
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowColor: 'rgba(255, 255, 255, 0.8)'
              }
            }
          },
          // 城市标记点系列
          {
            type: 'scatter',
            coordinateSystem: 'geo',
            symbol: 'circle',
            symbolSize: 6,
            data: Object.entries(this.heatGeoCoord).map(([name, coord]) => ({
              name,
              value: [...coord, 1]
            })),
            itemStyle: {
              color: '#fff',
              borderWidth: 1,
              borderColor: 'rgba(0, 242, 252, 0.8)'
            },
            label: {
              show: false,
              formatter: '{b}',
              position: 'right',
              textStyle: {
                color: '#fff'
              }
            },
            emphasis: {
              label: {
                show: true
              }
            }
          }
        ]
      };
    },

    // 开启定时器
    startInterval() {
      if (this.intervalId) {
        clearInterval(this.intervalId);
      }
      this.intervalId = setInterval(() => {
        this.reSelectMapRandomArea();
      }, 2000);
    },

    // 重新随机选中区域
    reSelectMapRandomArea() {
      const cityCount = Object.keys(this.heatGeoCoord).length;
      this.$nextTick(() => {
        try {
          const chart = this.$refs.heatMapRef.chart;
          let index = Math.floor(Math.random() * cityCount);

          // 避免重复选中同一个
          while (index === this.preSelectMapIndex || index >= cityCount) {
            index = Math.floor(Math.random() * cityCount);
          }

          // 取消上一个选中
          if (this.preSelectMapIndex !== -1) {
            chart.dispatchAction({
              type: 'downplay',
              seriesIndex: 1,
              dataIndex: this.preSelectMapIndex
            });
          }

          // 选中新区域并显示提示
          chart.dispatchAction({
            type: 'highlight',
            seriesIndex: 1,
            dataIndex: index
          });
          chart.dispatchAction({
            type: 'showTip',
            seriesIndex: 1,
            dataIndex: index
          });

          this.preSelectMapIndex = index;
        } catch (error) {
          console.error('热力图选择错误:', error);
        }
      });
    },

    // 初始化地图交互
    handleMapRandomSelect() {
      this.$nextTick(() => {
        try {
          const chart = this.$refs.heatMapRef.chart;
          const _self = this;

          // 初始选中
          setTimeout(() => {
            _self.reSelectMapRandomArea();
          }, 0);

          // 鼠标悬停时
          chart.on('mouseover', function(params) {
            if (params.seriesIndex === 1) { // 只处理标记点系列
              clearInterval(_self.intervalId);
              // 取消上一个选中
              if (_self.preSelectMapIndex !== -1) {
                chart.dispatchAction({
                  type: 'downplay',
                  seriesIndex: 1,
                  dataIndex: _self.preSelectMapIndex
                });
              }
              // 选中当前
              chart.dispatchAction({
                type: 'highlight',
                seriesIndex: 1,
                dataIndex: params.dataIndex
              });
              _self.preSelectMapIndex = params.dataIndex;
            }
          });

          // 鼠标移出时
          chart.on('globalout', function() {
            _self.startInterval();
          });

          this.startInterval();
        } catch (error) {
          console.error('热力图交互初始化错误:', error);
        }
      });
    }
  }
};
</script>
